using System;
using System.Collections.Generic;
using System.Text;
using FlexiCommerce.Components;

namespace FlexiCommerce.Collections
{
	/// <summary>
	/// Filters items not belonging to a certain parent item.
	/// </summary>
    public class ParentFilter : ItemFilter
    {
        int parentID;

        public ParentFilter(int parentID)
        {
            this.parentID = parentID;
        }

        public ParentFilter(PersistenceItem parent)
        {
            if (parent == null)
                throw new ArgumentNullException("parent");

            GetIHierarchalPersistenceItem(parent);

            this.parentID = parent.ID;
        }
        public ParentFilter(HierarchicalPersistenceItem parent)
        {
            if (parent == null)
                throw new ArgumentNullException("parent");

            PersistenceItem item = parent as PersistenceItem;
            if(item == null)
            {
                throw new FlexiException("{0} must inherit from PersistenceItem");
            }

            this.parentID = parent.ID;
        }

        public override bool Match(PersistenceItem item)
        {
            HierarchicalPersistenceItem hitem = GetIHierarchalPersistenceItem(item);
            while ((hitem = hitem.Parent) != null)
            {
                if (hitem.ID == parentID)
                    return true;
            }
            return false;
        }

        #region Static Methods
        public static void Filter(IList<PersistenceItem> items, HierarchicalPersistenceItem parent)
        {
            Filter(items, new ParentFilter(parent));
        }
        public static void Filter(IList<PersistenceItem> items, int parentID)
        {
            Filter(items, new ParentFilter(parentID));
        }
        #endregion

        private HierarchicalPersistenceItem GetIHierarchalPersistenceItem(PersistenceItem item)
        {
            HierarchicalPersistenceItem hitem = item as HierarchicalPersistenceItem;
            if(hitem == null)
            {
                throw new FlexiException("{0} must implement HierarchalPersistenceItem", item.GetType().Name);
            }
            return hitem;
        }
        private IList<HierarchicalPersistenceItem> GetIHierarchalPersistenceItems(IList<PersistenceItem> item)
        {
            IList<HierarchicalPersistenceItem> hitem = item as IList<HierarchicalPersistenceItem>;
            if (hitem == null)
            {
                throw new FlexiException("{0} must implement HierarchalPersistenceItem", item.GetType().Name);
            }
            return hitem;
        }
    }
}
